package com.zengqingfa.zookeeper.demo.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 *
 * @fileName: ZkConnectionWatcher
 * @author: zengqf3
 * @date: 2021-4-7 13:52
 * @description:
 */
public class ZkConnectionWatcher implements Watcher {

    static CountDownLatch countDownLatch = new CountDownLatch(1);

    static ZooKeeper zooKeeper;

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.None) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                System.out.println("连接创建成功");
                countDownLatch.countDown();
            } else if (event.getState() == Event.KeeperState.Disconnected) {
                System.out.println("断开连接");
            } else if (event.getState() == Event.KeeperState.Expired) {
                System.out.println("连接超时");
                try {
                    zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getState() == Event.KeeperState.AuthFailed) {
                System.out.println("认证失败");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        zooKeeper = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
        countDownLatch.await();
        System.out.println("会话id:" + zooKeeper.getSessionId());
        // 添加授权用户
        zooKeeper.addAuthInfo("digest", "admin:123456".getBytes());
        byte[] bs = zooKeeper.getData("/node1", false, null);
        System.out.println(new String(bs));
        Thread.sleep(5);
        zooKeeper.close();
        System.out.println("结束");
    }
}
